
#include <luaMathEx/luaInterpolation.h>
#include <algorithm>
#include<functional>
#include<boost/bind.hpp>
#include<complex>

LUA_MATH_EX_EXPORT_API
double math::interpolation(int n,const double arrx[],const double arry[],double x)
{
	int nlow, nhigh;
	return math::interpolation(n, arrx, arry,x,nlow,nhigh);
}

LUA_MATH_EX_EXPORT_API
double math::interpolation(int n,const double arrx[],const double arry[],double x,int &nlow, int& nhigh)
{
	const double* pos = std::find_if(arrx,arrx+n,boost::bind(std::greater<double>(),_1,x));
	int npos = std::distance(arrx,pos);
	nlow = std::max(npos-1,0);
	nhigh = std::min(n-1,npos);
	if( npos == 0) return arry[0];
	if( npos == n ) return arry[n-1];
	double res = arry[npos-1] + (x-arrx[npos-1])/(arrx[npos]-arrx[npos-1])*(arry[npos]-arry[npos-1]);
	return res;
}
double math::norphs(double phs)
{
	return std::arg( std::polar(1.0,phs) );
}


double math::array_max(int n,const double arrx[],int& idx)
{
	idx = 0;	
	for( int i = 1; i < n; i++)
	{
		if( arrx[idx] < arrx[i] )
			idx = i;		
	}
	return arrx[idx];
}

double math::array_min(int n,const double arrx[],int& idx)
{
	idx = 0;	
	for( int i = 1; i < n; i++)
	{
		if( arrx[idx] > arrx[i] )
			idx = i;		
	}
	return arrx[idx];
}

double math::array_max(int n,const double arrx[])
{
	int idx = 0;	
	return array_max(n,arrx,idx);
}

double math::array_min(int n,const double arrx[])
{
	int idx = 0;	
	return array_min(n,arrx,idx);
}
